package android.vstore.fragment;


import java.util.ArrayList;










import com.appvn2014.appstorevn.R;
import com.google.android.youtube.player.YouTubeStandalonePlayer;

import DTO.ImageDTO;
import DTO.VideoDTO;
import DTO.TopicDTO;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.vstore.activities.YoutubePlayerActivity;
import android.vstore.activities.BaseActivity;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import anroid.vstore.provider.Constant;

public class PageVideoFragment extends BaseFragment implements  OnScrollListener, OnItemClickListener {

	BaseActivity activity;
	private View rootView;
	private ListView lv_lstProds;
	public ArrayList<VideoDTO> _lstItem = new ArrayList<VideoDTO>();;
	public boolean isProductsLoading = false;
	public boolean isNomoreLoading = false;
	public static final int REFRESH_ALL_PAGE = 10;

	private ProgressBar pb;
	CustomAdapterVideo adapter;
	public boolean isReload;

	private int type;
	private Loader loader;
	Handler _parentHandler;
	int pagesize = 15;
	public static PageVideoFragment newInstance(BaseActivity activity,int id,int type,Handler parent)
	{
		PageVideoFragment page = new PageVideoFragment();
		page.activity = activity;
		page.isReload = true;
		page.id = id;
		page.type = type;
		page._parentHandler = parent;
		switch (type) {
		case Constant.VIDEO_HOT:
			page.name = activity.getString(R.string.video_hot);
			break;
		case Constant.VIDEO_NEW:
			page.name = activity.getString(R.string.video_new);
			break;
		case Constant.VIDEO_VIEWS:
			page.name = activity.getString(R.string.vide_view);
			break;

		default:
			break;
		}

		return page;


	}
	int ready = 0;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.fragment_sectionpage, container, false);
		InitGUI();
		Load();
		return rootView;
	}
	@Override
	public void onStart()
	{
		super.onStart();
	}
	@Override
	public void setMenuVisibility(final boolean visible) {
		super.setMenuVisibility(visible);
		if (!visible) {
			//not visible anymore
		}else{
			ready++;
			if (ready == 2 &&visible && _lstItem.size() == 0) {
				Load();
			}
			else {  }

		}
	}

	//	@Override
	//	public void setUserVisibleHint(boolean isVisibleToUser) {
	//	    super.setUserVisibleHint(isVisibleToUser);
	////	    if(!isReadyView)
	////	    	Oncre
	//	    ready++;
	//	    if (ready == 2 &&isVisibleToUser && _lstItem.size() == 0) {
	//	    	Load();
	//	    }
	//	    else {  }
	//	}

	// ==================================================================================
	// Reload list apk to check item row state
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		// reload
		Message sms = new Message();
		sms.what = REFRESH_ALL_PAGE;
		_messageHandler.handleMessage(sms);
	}

	// ==================================================================================

	@Override
	public void onPause()
	{
		if(loader != null)
			loader.cancel(true);
		super.onPause();
	}
	public void InitGUI()
	{

		lv_lstProds = (ListView)rootView.findViewById(R.id.lv_prods);
		pb = (ProgressBar) rootView.findViewById(R.id.pb_listview_loading);
		pb.setVisibility(View.INVISIBLE);
		lv_lstProds.setOnItemClickListener(this);
		lv_lstProds.setOnScrollListener(this);
		lv_lstProds.setItemsCanFocus(false);
		lv_lstProds.setDividerHeight(0);
		if(activity != null && activity.isVisible())
		{
			adapter = new CustomAdapterVideo(activity	, R.layout.item_list_prods	, _lstItem);
			lv_lstProds.setAdapter(adapter);
		}
	}
	public void Load()
	{
		if(isNomoreLoading )
			return;
		if(isReload )
		{
			_lstItem.clear();
		}
		loader = new Loader();
		(loader).execute();
		isReload = false;

	}
	public void Reload()
	{
		_lstItem = new ArrayList<VideoDTO>();
		adapter = new CustomAdapterVideo(activity	, R.layout.item_list_prods	, _lstItem);
		lv_lstProds.setAdapter(adapter);
		isReload = true;
		isNomoreLoading = false;
		Load();
	}
	public class Loader extends AsyncTask<String, Void, ArrayList<VideoDTO>>{
		@Override
		protected ArrayList<VideoDTO> doInBackground(String... params) {

			//			int pagesize = 10;
			ArrayList<VideoDTO> lstProds = null;
			switch (type) {
			case Constant.VIDEO_HOT:
				lstProds = DAO.VideoDAO.GetVideos(1,0,0,_lstItem.size()+pagesize);
				break;
			case Constant.VIDEO_NEW:
				lstProds = DAO.VideoDAO.GetVideos(0,0,1,_lstItem.size()+pagesize);
				break;
			case Constant.VIDEO_VIEWS:
				lstProds = DAO.VideoDAO.GetVideos(0,1,0,_lstItem.size()+pagesize);
				break;

			default:
				break;
			}
			if(lstProds.size() < _lstItem.size()+pagesize)
				isNomoreLoading = true;
			return lstProds;
		}      

		@Override
		protected void onPostExecute(ArrayList<VideoDTO> lstVipProd) {

			//			HideLoaderPending();
			isProductsLoading  = false;
			if(!activity.isVisible() && ! PageVideoFragment.this.isDetached())
				return;


			if(_lstItem != null && lstVipProd.size() > _lstItem.size())
			{
				int startindx = _lstItem.size();
				_lstItem.addAll(lstVipProd.subList(startindx, lstVipProd.size()));
				adapter.notifyDataSetChanged();
				//				adapter.notifyDataSetInvalidated();
			}
			//			adapter.notifyDataSetChanged();
		}

		@Override
		protected void onPreExecute() {
			if(isProductsLoading )
			{
				this.cancel(true);
				//				HideLoaderPending();
				return;
			}
			isProductsLoading = true;
			//			ShowLoaderPending();	
		}

		@Override
		protected void onProgressUpdate(Void... values) {
		}
	}

	protected void ShowLoaderPending()
	{		
		pb.setVisibility(View.VISIBLE);
	}
	protected void HideLoaderPending()
	{
		pb.setVisibility(View.INVISIBLE);
	}
	public Handler _messageHandler = new Handler(){
		@Override
		public void handleMessage(Message msg)
		{
			if(msg.what == REFRESH_ALL_PAGE)
			{
				//				if(adapter != null)
				//					adapter.notifyDataSetChanged();  
			}
		}
	};

	public class CustomAdapterVideo extends ArrayAdapter<VideoDTO>
	{
		ArrayList<VideoDTO> itemList;
		//		Boolean isInvalidated = true;
		//		String stt = getResources().getString(R.string.detail_activity_view_app);
		public Activity context;
		public LayoutInflater inflater;
		private final String TAG = "CustomAdapterVideo";

		public CustomAdapterVideo(Activity context, int textViewResource, ArrayList<VideoDTO> itemList) 
		{
			super(context, textViewResource, itemList);

			this.context = context;
			this.itemList = itemList; 

			this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		} 

		@Override 
		public int getCount() 
		{
			return itemList.size();
		}

		@Override
		public VideoDTO getItem(int position) 
		{
			return itemList.get(position);
		}

		@Override
		public long getItemId(int position) 
		{
			return 0;
		}

		public class ViewHolderProduct
		{
			public ImageView imgViewLogo;
			public TextView txtViewTitle;
			public Object lastImageUrl;
		}


		@Override
		public View getView(final int position, View convertView, ViewGroup parent) 
		{	    	
			final ViewHolderProduct holder;
			if(convertView == null) 
			{
				holder = new ViewHolderProduct();
				convertView = inflater.inflate(R.layout.item_list_videos, null);

				holder.imgViewLogo = (ImageView) convertView.findViewById(R.id.iv_itemlistvideo_logo);
				holder.txtViewTitle = (TextView) convertView.findViewById(R.id.tv_itemlistvideo_title);
				convertView.setTag(holder);
			}
			else
				holder = (ViewHolderProduct)convertView.getTag();

			VideoDTO bean = (VideoDTO) itemList.get(position);

			if(bean == null) return convertView;

			if (holder.lastImageUrl == null || !holder.lastImageUrl.equals(bean.imgURL)
					|| holder.imgViewLogo.getDrawable() == null) {
				// refresh image
				holder.lastImageUrl = bean.imgURL;
				ImageDTO.displayImage( bean.imgURL, holder.imgViewLogo); 
			} else {
				// do nothing, image did not change and does not need to be updated
			}


			holder.txtViewTitle.setText(bean.caption);
			return convertView;
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		// TODO Auto-generated method stub
		if(_lstItem != null && !isProductsLoading)
		{
			if(_lstItem.size()-2 > firstVisibleItem && _lstItem.size()-2 < firstVisibleItem+visibleItemCount)
			{
				Load();
			}
		}
	}
	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub

	}
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		VideoDTO video = _lstItem.get(arg2);
		if(video.link.contains("http"))
		{
			int indx = video.link.indexOf("=");
			if(indx != -1){
				String vidID = video.link.substring(indx+1,video.link.length());
//				activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//				Intent intent = YouTubeStandalonePlayer.createVideoIntent(
//						activity, Constant.YOUTUBE_DEVELOPER_KEY, vidID, 0, true, true);
				Intent intent = new Intent(activity, YoutubePlayerActivity.class);
				intent.putExtra("videoID", vidID);
				intent.putExtra("videoName", video.caption);
				activity.startActivityForResult(intent,0);
			}
		}
	}



}
